package com.htsk.city.services.wechat.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.service.WxPayService;
import com.htsk.city.services.core.constant.CacheConstants;
import com.htsk.city.services.core.dao.CityDao;
import com.htsk.city.services.core.dao.CityServiceSubCategoryDao;
import com.htsk.city.services.core.dao.ServiceCategoryDao;
import com.htsk.city.services.core.dao.ServiceSubCategoryDao;
import com.htsk.city.services.core.domain.*;
import com.htsk.city.services.core.entity.R;
import com.htsk.city.services.core.entity.ServiceSubCategoryVO;
import com.htsk.city.services.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CityService {

    @Resource
    private CityDao cityDao;

    @Resource
    private ServiceCategoryDao serviceCategoryDao;

    @Resource
    private ServiceSubCategoryDao serviceSubCategoryDao;
    @Resource
    private CityServiceSubCategoryDao cityServiceSubCategoryDao;
    //@Resource
    WxPayService wxPayService;

    /**
     * 城市列表
     * @return
     */
    public R<List<City>> listCity(){
        return R.ok(cityDao.findByStatusAndDelFlag(1,0));
    }

    /**
     * 设置当前城市
     * @param cityId
     * @return
     */
    public R<Boolean> setCurrentCity(Long cityId ){
        StpUtil.getSession().set(CacheConstants.CURRENT_CITY_ID,cityId);
        return R.ok(true);
    }

    /**
     * 当前城市开通的一级大类服务
     * @return
     */
    public R<List<ServiceCategory>> getCityService(Long cityId){
//        Long cityId=StpUtil.getSession().getLong(CacheConstants.CURRENT_CITY_ID);
        return R.ok(serviceCategoryDao.queryByCityId(cityId));
    }

    /**
     * 根据服务大类查询子类
     * @param serviceCategoryId
     * @return
     */
    public R<List<Map<String,Object>>> getCitySubService(Long cityId,Long serviceCategoryId){
//        Long cityId=StpUtil.getSession().getLong(CacheConstants.CURRENT_CITY_ID);
        List<Map<String,Object>> result = serviceSubCategoryDao.queryByCityId(cityId,serviceCategoryId);
        return R.ok(result);
    }

    /**
     * 获取城市服务详情
     * @param serviceId
     * @return
     */
    public R<ServiceSubCategoryVO> serviceDetail(Long serviceId){
        CityServiceSubCategory cityServiceSubCategory=cityServiceSubCategoryDao.getById(serviceId);
        ServiceSubCategory serviceSubCategory=serviceSubCategoryDao.getById(cityServiceSubCategory.getServiceSubCategoryId());
        return R.ok(new ServiceSubCategoryVO(serviceSubCategory,cityServiceSubCategory));
    }

    public R createOrder(WxUser wxUser,Long serviceId){
        ServiceSubCategoryVO serviceSubCategoryVO=serviceDetail(serviceId).getData();
        String orderNo=generateOrderNo("WX");
        try {
            //生成订单记录
            OrderMaster orderMaster=new OrderMaster();

            orderMaster.setOrderNo(orderNo);

            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setBody(serviceSubCategoryVO.getServiceSubCategoryName());
            orderRequest.setOutTradeNo(orderNo);
            orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(serviceSubCategoryVO.getServicePrice().toString()));//元转成分
            orderRequest.setOpenid(wxUser.getOpenId());
            orderRequest.setSpbillCreateIp("userIp");
            orderRequest.setTimeStart("yyyyMMddHHmmss");
            orderRequest.setTimeExpire("yyyyMMddHHmmss");

            return R.ok(wxPayService.createOrder(orderRequest));
        } catch (Exception e) {
            log.error("微信支付失败！订单号：{},原因:{}", orderNo, e.getMessage());
            e.printStackTrace();
            return R.fail("支付失败，请稍后重试！");
        }
    }

    @Resource
    RedisCache redisCache;

    public String generateOrderNo(String prefix) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());

        // 前缀(2位) + 年月日(8位) + 业务类型(2位) + 自增序列(6位)
        String bizType = "01"; // 01-普通订单 02-秒杀订单等
        String key = "order_no:" + dateStr + ":" + bizType;
        long sequence = 1;

        return prefix + dateStr + bizType + String.format("%06d", sequence);
    }
}
